package com.zlp.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.model.OSSObject;
import com.zlp.common.constants.OSSConstant;
import com.zlp.config.OSSTemplate;
import com.zlp.dto.UploadResp;
import com.zlp.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Collections;
import java.util.List;

@Service
@Slf4j(topic = "FileServiceImpl")
public class FileServiceImpl implements FileService {

    @Resource
    private OSSTemplate ossTemplate;

    /**
     * 目前所有文件都存放在该命名空间下
     */
    private final static String bucketName = OSSConstant.BUCKE_NAME;


    @Override
    public String uploadFile(String filePath, MultipartFile file) {

        log.info("uploadFile.req bucketName={}", bucketName);
        String fileName = IdUtil.simpleUUID() + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());
        if (StringUtils.isNotBlank(filePath)) {
            fileName = filePath + StrUtil.SLASH + fileName;
        }
        String url;
        try {
            ossTemplate.putObject(bucketName, fileName, file.getInputStream());
            url = OSSConstant.HTTP_PREFIX + bucketName + StrUtil.DOT + OSSConstant.DOMAIN + StrUtil.SLASH + fileName;
        } catch (Exception e) {
            log.error("上传失败", e);
            return null;
        }
        log.info("uploadFile.resp url={}",url);
        return url;
    }

    @Override
    public UploadResp uploadFileProgress(MultipartFile file, String type, Long fileSize, String uploadNo) {


        log.info("uploadFileProgress.req type={}", type);
        UploadResp uploadResp = new UploadResp();
        String filename = file.getOriginalFilename();
        uploadResp.setFileName(filename);
        String extName = FileUtil.extName(filename);
        String filePath = IdUtil.simpleUUID() + StrUtil.DOT + extName;
        if (!org.springframework.util.StringUtils.isEmpty(type)) {
            filePath = type + StrUtil.SLASH + filePath;
        }
        // 转换MultipartFile 转换为file
        File newFile = new File(filename);
        FileOutputStream os = null;
        try {
            os = new FileOutputStream(newFile);
            os.write(file.getBytes());
            file.transferTo(newFile);
            ossTemplate.putObject(bucketName, filePath, newFile, uploadNo, fileSize);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        uploadResp.setFileUrl(filePath);
        delLocalFile(filename);
        return uploadResp;
    }

    /**
     * 删除上传生成文件
     *
     * @param filename
     * @date: 2021/3/19 14:03
     * @return: void
     */
    private void delLocalFile(String filename) {
        String property = System.getProperty("user.dir");
        String localUrl = property + StrUtil.SLASH + filename;
        log.info("delLocalFile localUrl={}", localUrl);
        File loacaFile = new File(localUrl);
        if (loacaFile.isFile() && loacaFile.exists()) {
            loacaFile.delete();
        }
    }

    @Override
    public void downFile(String dowUrl, HttpServletResponse response) {

        ossTemplate.getObject(dowUrl, response);
    }

    @Override
    public void downloadFile(String objectName, String localFileName) {

        log.info("downloadFile.req objectName={},localFileName={}", objectName, localFileName);

        ossTemplate.downloadFile(objectName, localFileName);

    }

    @Override
    public List<String> listFile(String filePath) {


        log.info("listFile.req filePath={}", filePath);
        List<String> listFile = ossTemplate.listFile(filePath);
        return CollectionUtil.isNotEmpty(listFile) ? listFile : Collections.EMPTY_LIST;
    }

    @Override
    public void delFile(String delFileUrl) {

        log.info("delFile.req delFileUrl={}", delFileUrl);
        ossTemplate.delFile(delFileUrl);
    }

    @Override
    public ResponseEntity<byte[]> downloadObject(String fileName) {

        fileName = "test/edcb724a202d4497984cc48a240408d3.txt";
        OSSObject ossObject = ossTemplate.getObject(fileName);
        HttpHeaders headers = new HttpHeaders();
        ResponseEntity<byte[]> entity = null;
        BufferedInputStream bis;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[10240];
        try {
            bis = new BufferedInputStream(ossObject.getObjectContent());
            while (true) {
                int len = bis.read(buf);
                if (len < 0) {
                    break;
                }
                bos.write(buf, 0, len);
            }
            //将输出流转为字节数组，通过ResponseEntity<byte[]>返回
            byte[] b = bos.toByteArray();
            log.info("接收到的文件大小为：" + b.length);
            HttpStatus status = HttpStatus.OK;
            String imageName = "0001.txt";
            headers.setContentType(MediaType.ALL.APPLICATION_OCTET_STREAM);
            headers.add("Content-Disposition", "attachment;filename=" + imageName);
            entity = new ResponseEntity<>(b, headers, status);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return entity;
    }


}
